package com.six.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.six.domain.dto.CreateStoreDto;
import com.six.domain.dto.PayConfigDto;
import com.six.domain.dto.PrinterDto;
import com.six.domain.entity.PayConfig;
import com.six.domain.entity.Printer;
import com.six.domain.entity.Store;
import com.six.domain.entity.SysDict;
import com.six.domain.entity.User;
import com.six.domain.vo.PrinterVo;
import com.six.service.SysAdminService;
import com.six.service.StoreService;
import com.six.service.UserService;
import com.six.util.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.nio.file.AccessDeniedException;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/api/admin")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN')")
public class SysAdminController {

    /* ======= 依赖注入 ======= */
    private final SysAdminService sysAdminService;
    private final StoreService    storeService;
    private final UserService     userService;

    /* -------------------------------------------------
     * 1. 门店管理（原 UserController 迁移）
     * ------------------------------------------------- */
    @PostMapping("/store")
    public Result<Map<String,String>> createStore(@Valid @RequestBody CreateStoreDto dto) {
        Map<String,String> account = storeService.createStoreWithManager(dto); // 只调一次
        return Result.success(account);
    }

    @GetMapping("/stores/page")
    public Result<Page<Store>> listStores(
            @RequestParam(defaultValue = "") String keyword,
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size
    ) {
        Page<Store> page = new Page<>(current, size);
        return Result.success(sysAdminService.listStores(keyword, page));
    }

    @GetMapping("/stores/{id}")
    public Result<Store> getStore(@PathVariable Long id) {
        return Result.ok(storeService.getStore(id));
    }

    @DeleteMapping("/stores/{id}")
    public Result<Void> deleteStore(@PathVariable Long id) {
        sysAdminService.deleteStore(id);
        return Result.ok();
    }

    /* -------------------------------------------------
     * 2. 员工账号（原 UserController 迁移）
     * ------------------------------------------------- */
    @GetMapping("/waiters")
    public Result<List<User>> listAllWaiters() {
        return Result.ok(userService.listWaitersByStore(null));
    }

    @GetMapping("/stores/{storeId}/waiters")
    public Result<List<User>> listWaitersByStore(@PathVariable Long storeId,
                                                 Authentication authentication) throws AccessDeniedException {
        return Result.ok(userService.listWaitersByStore(storeId, authentication));
    }


    /* -------------------------------------------------
     * 3. 打印机配置
     * ------------------------------------------------- */
    @PostMapping("/printers")
    public Result<Void> savePrinter(@Valid @RequestBody PrinterDto dto) {
        sysAdminService.savePrinter(dto);
        return Result.ok();
    }

    @GetMapping("/printers")
    public Result<List<PrinterVo>> listPrinters(@RequestParam(required = false) Long storeId) {
        List<PrinterVo> list = sysAdminService.listPrinters(storeId);

        return Result.success(list);
    }
    /* 5. 修改打印机 */
    @PutMapping("/printers/{id}")
    public Result<Void> updatePrinter(@PathVariable Long id,
                                      @Valid @RequestBody PrinterDto dto) {
        dto.setId(id);          // 把主键带进去
        sysAdminService.updatePrinter(dto);
        log.info("👉 更新打印机 id={} , enabled={}", id, dto.getEnabled());
        return Result.ok();
    }

    /* 6. 删除打印机 */
    @DeleteMapping("/printers/{id}")
    public Result<Void> deletePrinter(@PathVariable Long id) {
        sysAdminService.deletePrinter(id);
        return Result.ok();
    }

    /* -------------------------------------------------
     * 4. 支付通道配置
     * ------------------------------------------------- */
    @PostMapping("/pay-channels")
    public Result<Void> savePayConfig(@Valid @RequestBody PayConfigDto dto) {
        sysAdminService.savePayConfig(dto);
        return Result.ok();
    }

    @GetMapping("/pay-channels")
    public Result<List<PayConfig>> listPayConfigs(@RequestParam Long storeId) {
        return Result.success(sysAdminService.listPayConfigs(storeId));
    }

    /* -------------------------------------------------
     * 5. 全局字典
     * ------------------------------------------------- */
    @GetMapping("/dicts/{type}")
    public Result<List<SysDict>> listDict(@PathVariable String type) {
        return Result.success(sysAdminService.listDict(type));
    }

    @PutMapping("/dicts/{type}")
    public Result<Void> updateDict(@PathVariable String type,
                                   @RequestBody List<SysDict> items) {
        sysAdminService.updateDict(type, items);
        return Result.ok();
    }
}